import axios from 'axios'
import { Message, Notification } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
function queryParse (query) {
  let res = []
  for (let k in query) {
    res.push(`${encodeURIComponent(k)}=${encodeURIComponent(query[k])}`)
  }
  return res.join('&')
}
// https://chddadm.dzpk360.com/, https://xishengguoji.dlc-sz.com
const baseURL = process.env.NODE_ENV === 'production' ? 'https://xishengguoji.dlc-sz.com' : '/api'
const service = axios.create({
  baseURL,
  timeout: 10000
})

export const json2fd = json => {
  const fd = new FormData()
  for (let k in json) {
    fd.append(k, json[k])
  }
  return fd
}
service.interceptors.request.use(config => {
  if (store.getters.token) {
    config.headers['Authorization'] = getToken()
  }

  if (!(config.data instanceof FormData)) {
    config.headers['Content-Type'] = "application/x-www-form-urlencoded; charset=UTF-8"
    config.data = queryParse(config.data)
 
  }

  return config
}, error => {
  console.log(error) // for debug
  Promise.reject(error)
})

service.interceptors.response.use(
  response => {
   const res = response.data;
   console.log(`res------------>`, res);
   if (res.code === 1) {
    return res 
   } else if (res.code === 3 || res.code === 21 || res.code === 403) {
    // console.log(`token`,res)
    // res.code === 403 || 
    Notification({
      title: '警告',
      message: '您的登录凭证已过期，请重新登录,2秒后自动退出系统',
      type: 'warning'
    })
   } else {
    Message({
      message: res.msg,
      type: 'error',
      duration: 5 * 1000
    });
    return Promise.reject(res)
   }
  },
  error => {
    console.log('err', error)// for debug
    Message({
      message: error.message || error.msg,
      type: 'error',
      duration: 5 * 1000
    })
    // setTimeout(() => {
    //   store.dispatch('FedLogOut').then(() => {
    //     location.reload();// 为了重新实例化vue-router对象 避免bug
    //   }); 
    // }, 2000);
    return Promise.reject(error)
  })

export default service
